package main

import (
	"flag"
	"fmt"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"

	"github.com/golang/glog"
)

func main() {
	flag.Set("v", "4")
	glog.V(2).Info("Starting http server...")

	http.HandleFunc("/", rootHandler)
	http.HandleFunc("/healthz", healthzHandler)
	http.HandleFunc("/readEnv", readEnvHander)
	http.HandleFunc("/log", logHander)

	error := http.ListenAndServe(":8080", nil)
	if error != nil {
		glog.Fatalln(error)
	}
}

/**
curl -v host:8080/
*/
func rootHandler(w http.ResponseWriter, r *http.Request) {

	delay := randInt(10, 2000)
	time.Sleep(time.Millisecond * time.Duration(delay))
	for k, v := range r.Header {
		fmt.Println(k, "=", v)
		fmt.Fprintf(w, "%s=%s\n", k, v)
	}
	req, err := http.NewRequest("GET", "http://service1", nil)
	if err != nil {
		fmt.Printf("%s", err)
	}
	lowerCaseHeader := make(http.Header)
	//将Header中的Key转为小写
	for key, value := range r.Header {
		lowerCaseHeader[strings.ToLower(key)] = value
	}
	glog.Info("headers:", lowerCaseHeader)
	//重新赋值请求的Header
	req.Header = lowerCaseHeader
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		glog.Info("HTTP get failed with error: ", "error", err)
	} else {
		glog.Info("HTTP get succeeded")
	}
	if resp != nil {
		resp.Write(w)
	}
	glog.V(4).Infof("Respond in %d ms", delay)
}

func randInt(min int, max int) int {
	rand.Seed(time.Now().UTC().UnixNano())
	return min + rand.Intn(max-min)
}

/**
curl -v host:8080/healthz
*/
func healthzHandler(w http.ResponseWriter, r *http.Request) {

	fmt.Fprintf(w, "ok\n")
}

/**
curl -v host:8080/readEnv?env=XXXX
*/
func readEnvHander(w http.ResponseWriter, r *http.Request) {

	queryForm, error := url.ParseQuery(r.URL.RawQuery)
	if error == nil && len(queryForm["env"]) > 0 {
		goRoot := os.Getenv(queryForm["env"][0])
		if len(goRoot) < 1 {
			fmt.Fprintf(w, "未找到%s 对应的环境变量值。\n", queryForm["env"][0])
		} else {
			//设置header顺序问题，在写内容前生效，反之不生效
			w.Header().Set(queryForm["env"][0], goRoot)
			fmt.Fprintf(w, "goRoot=%s\n", goRoot)
		}
	} else {
		fmt.Fprintf(w, "请使用/readEnv?env=KEY,的方式\n")
	}
}

/**
curl -v host:8080/log
*/
func logHander(w http.ResponseWriter, r *http.Request) {

	// ip := r.RemoteAddr
	forwarded := r.Header.Get("X-FORWARDED-FOR")
	if forwarded == "" {
		forwarded = r.RemoteAddr
	}
	code := w.Header().Get("status")
	fmt.Fprintf(w, "ip:%s,code:%s", strings.Split(forwarded, ":")[0], code)
}
